package com.scrapy.regex;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.List;
import java.util.Properties;
/**
 * 解析xml
 * 把xml放入到Java封装的对象中
 * Created by wanter on 2016/11/7.
 */
public class RegexContent {
    private Document document;
    private static SAXReader reader = null;
    private Properties propertie;
    static{
        reader = new SAXReader();
    }

    /**
     * 传入xml的文件路径
     * @param xmlName xml配置文件地址
     */
    public RegexContent(String xmlName) throws DocumentException {
        this.document = reader.read(xmlName);
        this.paseXml();

    }

    /**
     * 开始解析xml
     */
    private void paseXml(){
        this.propertie = new Properties();
        Document doc = this.getDocument();
        Element root = doc.getRootElement();
        List<Element> lists = root.elements();
        for(Element el : lists){
            pase(el, propertie);
        }

    }

    /**
     * @return 返回这个文本对象
     */
    private Document getDocument(){
        return this.document;
    }

    /**
     * 解析出一级子标签
     * 根据一级子标签找到对应的解析方法
     * @param ele 传入的一级标签
     * @param properties 传入的
     */
    private void pase(Element ele, Properties properties){
        String firstName = ele.getName();
        if("joker".equalsIgnoreCase(firstName)){
            paseJoker(ele,properties);
        }else{
            System.err.println("没有找到对应的子标签"+firstName);
        }
    }

    /**
     * 解析文档中的Joker标签
     * @param ele Element子对象
     * @param properties 配置文件存放的地方
     */
    private void paseJoker(Element ele, Properties properties){
        List<Element> listElements = (List<Element>)ele.elements();
        for (Element e:listElements) {
            List<Element> lists = e.elements();
            for(Element el:lists){
                properties.setProperty(el.getName(),el.getText().trim());
            }

        }
    }


    public Properties getProperties(){
        return this.propertie;
    }
}
